﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;

namespace RL
{
    /// <summary>
    /// Логика взаимодействия для wStationMoneyTable.xaml
    /// </summary>
    public partial class wStationMoneyTable : Window
    {

        public routelistEntities ContextDB;
        //public routelistEntities ContextDB
        //{
        //    get { return (routelistEntities)GetValue(ContextDBProperty); }
        //    set { SetValue(ContextDBProperty, value); }
        //}

        //// Using a DependencyProperty as the backing store for ContextDB.  This enables animation, styling, binding, etc...
        //public static readonly DependencyProperty ContextDBProperty =
        //    DependencyProperty.Register("ContextDB", typeof(routelistEntities), typeof(wStationMoneyTable), new UIPropertyMetadata(null));




        public VokzalTable VokzalTable
        {
            get { return (VokzalTable)GetValue(VokzalTableProperty); }
            set { SetValue(VokzalTableProperty, value); }
        }

        // Using a DependencyProperty as the backing store for VokzalTable.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty VokzalTableProperty =
            DependencyProperty.Register("VokzalTable", typeof(VokzalTable), typeof(wStationMoneyTable), new UIPropertyMetadata(null, new PropertyChangedCallback(propVokzalTable)));

        public static void propVokzalTable(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            wStationMoneyTable item = d as wStationMoneyTable;
            if (null == item) return;
            VokzalTable it = e.NewValue as VokzalTable;
            if (null == it) return;
            if (null == item.ContextDB) return;
            item.grid1.DataContext = it;
        }



        public int VokzalTableID
        {
            get { return (int)GetValue(VokzalTableIDProperty); }
            set { SetValue(VokzalTableIDProperty, value); }
        }

        // Using a DependencyProperty as the backing store for VokzalTableID.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty VokzalTableIDProperty =
            DependencyProperty.Register("VokzalTableID", typeof(int), typeof(wStationMoneyTable), new UIPropertyMetadata(0, new PropertyChangedCallback(propVokzalTableID)));

        public static void propVokzalTableID(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            wStationMoneyTable item = d as wStationMoneyTable;
            if (null == d) return;
            int val = (int)e.NewValue;
            VokzalTable it = (from o in item.ContextDB.VokzalTable where o.id == val select o).FirstOrDefault();
            if (null == it) return;
            item.VokzalTable = it;
        }

        public wStationMoneyTable()
        {
            InitializeComponent();
            ContextDB = new routelistEntities();
        }

        private System.Data.Objects.ObjectQuery<VokzalTable> GetVokzalTableQuery(routelistEntities routelistEntities)
        {
            // Автоматически созданный код

            System.Data.Objects.ObjectQuery<RL.VokzalTable> vokzalTableQuery = routelistEntities.VokzalTable;
            // Для явной загрузки данных, возможно, потребуется добавить методы Include, аналогичные показанным ниже:
            // vokzalTableQuery = vokzalTableQuery.Include("VokzalTable.RouteList").
            // Дополнительные сведения см. по ссылке http://go.microsoft.com/fwlink/?LinkId=157380
            // Возвращает ObjectQuery.
            return vokzalTableQuery;
        }

        private IEnumerable<Routes> getQueryRoutes(routelistEntities routelistEntities)
        {
            if (null == routelistEntities) return null;
            IEnumerable<Routes> query = from o in routelistEntities.Routes orderby o.number where o.del == false select o;
            return query;
        } 

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            RL.routelistEntities routelistEntities;
            if (null == ContextDB)
                routelistEntities = new RL.routelistEntities();
            else
                routelistEntities = ContextDB;
            CollectionViewSource cvsRoutes = (CollectionViewSource)this.FindResource("routeSource");
            cvsRoutes.Source = getQueryRoutes(routelistEntities);
            CollectionViewSource cvsStation = (CollectionViewSource)this.FindResource("stationSource");
            cvsStation.Source = from o in routelistEntities.Station orderby o.name select o;
            // Загрузить данные в VokzalTable. Можно изменить этот код как требуется.
            //System.Windows.Data.CollectionViewSource vokzalTableViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vokzalTableViewSource")));
            //System.Data.Objects.ObjectQuery<RL.VokzalTable> vokzalTableQuery = this.GetVokzalTableQuery(routelistEntities);
            //vokzalTableViewSource.Source = vokzalTableQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
        }

        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            if (SaveData())
            {
                try
                {
                    DialogResult = true;
                }
                catch (Exception)
                {
                }
                Close();
            }
        }

        private bool IsModified()
        {
            bool bResult = false;
            if (null == ContextDB) return false;
            bResult = ContextDB.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added).Count() > 0 || ContextDB.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted).Count() > 0 || ContextDB.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified).Count() > 0;
            return bResult;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (IsModified())
            {
                var result = MessageBox.Show("Сохранить изменения?", "Предупреждение", MessageBoxButton.YesNoCancel, MessageBoxImage.Exclamation, MessageBoxResult.Yes);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        if (false == SaveData())
                        {
                            e.Cancel = true;
                        }
                        else
                        {
                            try
                            {
                                DialogResult = true;
                            }
                            catch (Exception)
                            {
                            }
                        }
                        break;
                    case MessageBoxResult.Cancel:
                        e.Cancel = true;
                        break;
                }

            }
        }

        private bool SaveData()
        {
            bool bResult = true;
            try
            {
                ContextDB.SaveChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), Properties.Resources.DataSavingError, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                bResult = false;
            }
            return bResult;
        }

        private void InitRouteSource()
        {
        }

        private void LoadRoute()
        {
            if (ContextDB == null) return;
            if (null == VokzalTable.RouteList) return;
            Routes rt = (from o in VokzalTable.RouteList.RouteListSchedule where o.time_departure.Trim() == VokzalTable.time_departure.Trim() select o.Routes).FirstOrDefault();
            if (null == rt)
            {
                MessageBox.Show("Маршрутов с указанным временем выхода не найдено");
                return;
            }
            VokzalTable.Routes = rt;
            VokzalTable.id_route = rt.id;
        }

        private void SelectRouteListButton_Click(object sender, RoutedEventArgs e)
        {
            RouteList rl = null;
            wRouteList wnd = new wRouteList();
            wnd.SelectMode = true;
            //wnd.ContextDB = ContextDB;
            if (wnd.ShowDialog() == false)
            {
                return;
            }
            rl = wnd.RouteList;
            if (null == rl) return;
            RouteListSchedule sch = (from o in rl.RouteListSchedule where o.time_departure.Trim() != "" orderby o.time_departure select o).FirstOrDefault();
            Routes sel_rt;
            if (null == sch)
            {
                MessageBox.Show("В выбранном путевом листе нет информации о расписании. Выберите маршрут.");
                wRouteRegistry ws = new wRouteRegistry();
                ws.ContextDB = ContextDB;
                if (false == ws.ShowDialog())
                    return;
                sel_rt = ws.Route;
                if (null == sel_rt) return;
            }
            else
            {
                sel_rt = sch.Routes;
            }
            if (null == sel_rt) return;

            //VokzalTable.RouteList = rl;
            VokzalTable.id_routelist = rl.id;
            VokzalTable.id_route = sel_rt.id;
        }

        private void time_departureTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            LoadRoute();
        }

        private void qnt_ticketsTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            double insurance = 0.0;
            int qnt = 0;
            try
            {
                VokzalTable dt = grid1.DataContext as VokzalTable;
                if (null == dt) return;
                if (dt.Routes.RouteType.insurance.HasValue && dt.Routes.RouteType.insurance.Value == true)
                {
                    Int32.TryParse(qnt_ticketsTextBox.Text, out qnt);
                    insurance = qnt * 1.5;
                }
                dt.sum_insurance = (float)insurance;
            }
            catch (Exception)
            {
            }
        }
        

    }

    //[ValueConversion(typeof(RouteList), typeof(String))]
    //public class RouteListTypeConverter : IValueConverter
    //{

    //    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    //    {
    //        string result="";
    //        if (null == value) return "<Не выбран>";
    //        RouteList rl = value as RouteList;
    //        if (null == rl) return result;
    //        result = string.Format("{0} от {1}", rl.nomdog, rl.datedoc);
    //        return result;
    //    }

    //    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    //    {
    //        throw new NotImplementedException();
    //    }
    //}

    [ValueConversion(typeof(Int32), typeof(String))]
    public class RouteListTypeConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            DateTime dt = DateTime.Now;
            string result = "";
            if (null == value) return "<Не выбран>";

            int rl_i = (int)value;
            routelistEntities db = new routelistEntities();
            RouteList rl = (from o in db.RouteList where o.id == rl_i select o).FirstOrDefault();
            if (null == rl) return result;
            result = string.Format("{0} от {1}", rl.nomdog, rl.dt_datedoc.HasValue ? rl.dt_datedoc.Value.ToString("dd/MM/yyyy") : "");
            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    //[ValueConversion(typeof(Routes), typeof(String))]
    //public class RoutesTypeConverter : IValueConverter
    //{
    //    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    //    {
    //        if (null == value) return "<не выбран>";
    //        Routes item = value as Routes;
    //        if (null == item) return "";
    //        string result = string.Format("{0} {1}",item.number.Trim(), item.name.Trim());
    //        return result;
    //    }

    //    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    //    {
    //        throw new NotImplementedException();
    //    }
    //}
    [ValueConversion(typeof(int), typeof(String))]
    public class RoutesTypeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (null == value) return "<не выбран>";
            int item_i = (int)value;
            routelistEntities db = new routelistEntities();
            Routes item = (from o in db.Routes where o.id == item_i select o).FirstOrDefault();
            if (null == item) return "";
            string result = string.Format("{0} {1}", item.number.Trim(), item.name.Trim());
            return result;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
